<template>
	<div>
		<div class="container">
			<h2 style="text-align: center;">总控材料计划</h2>
			<div class="toolbar">
				<a-form ref="searchRef" :model="searchState" @finish="current = 1; loading = true; initData()">
					<!-- <flow-query-button @change="changeflowStatus"></flow-query-button> -->
					<a-row :gutter="20">
						<a-col :span="8">
							<a-form-item label="城市公司/专业公司">
								<a-select v-model:value="searchState.company_id" :show-search="true" placeholder="请选择城市公司/专业公司" :options="companyOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="选择项目">
								<a-select v-model:value="searchState.project_id" :show-search="true" placeholder="请选择项目" :options="innerProjectOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="创建人">
								<a-select v-model:value="searchState.opr_id" :show-search="true" placeholder="请选择创建人" :options="userOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="20">
						<a-col :span="8">
							<a-form-item label="计划名称">
								<a-input v-model:value="searchState.name" placeholder="请输入" allow-clear></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item>
								<a-space>
									<a-button type="primary" html-type="submit">
										<search-outlined />搜索
									</a-button>
									<a-button v-permission="16" type="primary" danger @click="router.push('plan/create')">
										<plus-outlined />创建新计划
									</a-button>
								</a-space>
							</a-form-item>
						</a-col>
						<a-col style="padding: 10px 0;" :span="8"></a-col>
					</a-row>
				</a-form>
			</div>

			<div class="mt-2">
				<!--
				v-if="!loading"使得:default-expand-all-rows="true"生效
				-->
				<a-table v-if="!loading" :columns="columns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="planSource" :pagination="pagination" :loading="loading" @change="initData">
					<template #bodyCell="{ column, record }">
						<template v-if="column.key === 'operation'">
							<a-space>
								<!-- <a-button v-if="record.parent_id === 0" type="link" @click="showPlan(record)">
									<diff-outlined />工号计划汇总
								</a-button>

								<a-button v-if="record.parent_id === 0" type="link" @click="router.push(`/plan/create?parent_id=${record.id}`)">
									<plus-outlined />更新计划
								</a-button>-->
								<a-button v-permission="19" type="link" @click="showPlan(record)">查看</a-button>

								<a-button v-permission="21" type="link" @click="editPlan(record)">
									<edit-outlined />修改
								</a-button>
								<a-button v-permission="100" type="link" style="color:#ff7875" @click="deletePlan(record.id)">
									<delete-outlined />删除
								</a-button>

								<!-- <a-button v-if="record.parent_id === 0" type="link" @click="router.push(`/plan/summary/${record.id}`)">
									<partition-outlined :rotate="180" />总控计划汇总
								</a-button>-->
							</a-space>
						</template>
						<!--
						<template v-else-if="column.key === 'flowStatus'">
							<div>
								<div v-if="record.flow_status === 2">已完成</div>

								<flow-model v-else :module-id="'plan'" :item-id="record.id" @change="changeFlowStatusData2"></flow-model>
							</div>
						</template>
						-->
					</template>
				</a-table>
			</div>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref, computed, getCurrentInstance } from "vue";
import { useRouter, useRoute } from "vue-router";

const { proxy } = getCurrentInstance();
import dayjs from "dayjs";

import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, PartitionOutlined, DiffOutlined } from "@ant-design/icons-vue";

import { post } from "../utils";
const route = useRoute();
const router = useRouter();
const query = route.query;
import { usePagination } from "vue-request";
const itemFlowId = ref({});
const itemDepartments2 = ref({});

const changeFlowStatusData2 = e => {
	if (e.act === "flowInfoData") {
		var depts = e.data.flowType.departments;
		itemDepartments2.value = {
			...itemDepartments2.value,
			[e.data.item_id]: depts
		};
		itemFlowId.value = { ...itemFlowId.value, [e.data.item_id]: e.data.id };
	}
};
const searchRef = ref();
const searchState = reactive({});
const projectOptions = ref([]);
const companyOptions = ref([]);

const getProjects = async () => {
	const projectResult = await post("department/projects?type=3", { page_size: 1000 });
	projectOptions.value = projectResult.data.map(d => {
		return {
			value: d.id,
			label: d.name,
			parseIds: d.parent_ids.split(',').map(item => parseInt(item)),
		};
	});
};
if (!projectOptions.value.length) {
	getProjects();
}
post("department/projects?type=2", {
	parent_ids: JSON.stringify([78, 24])
}).then(({ data }) => {
	companyOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
const innerProjectOptions = computed(() => {
	searchState.project_id = null;
	if (searchState.company_id) {
		return projectOptions.value.filter(item => {
			return item.parseIds.includes(searchState.company_id);
		});
	} else {
		return projectOptions.value;
	}
});
const userOptions = ref([]);
post("filter/user").then(data => {
	userOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.fullname || d.username
		};
	});
});
const columns = [
	{
		title: "序号",
		dataIndex: "id",
		key: "id",
		width: 120,
		align: "left",
		fixed: "left"
	},
	{
		title: "项目名称",
		dataIndex: "project",
		sorter: false,
		width: 150,
		ellipsis: true,
		fixed: "left",
		customRender: ({ text, record, index, column }) => {
			return text.name;
		}
	},
	{
		title: "计划名称",
		dataIndex: "name",
		sorter: false,
		width: 150,
		ellipsis: true,
		fixed: "left"
	},
	{
		title: "计划编号",
		dataIndex: "code",
		sorter: false,
		width: 150,
		ellipsis: true,
		fixed: "left"
	},

	// {
	// 	title: "计划编号",
	// 	dataIndex: "code",
	// 	sorter: false,
	// 	width: 150,
	// 	ellipsis: true
	// },
	{
		title: "计划日期",
		dataIndex: "create_time",
		width: 150,
		align: "center",
		customRender: ({ text }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "计划创建人",
		dataIndex: "opr_user",
		width: 120,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			//return (text || []).map(d => `${d.fullname || d.username}`).join(",");
			return text.fullname || text.username;
		}
	},
	{
		title: "最后更新时间",
		dataIndex: "update_time",
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 150,
		align: "center"
	}
];
const tableScroll = computed(() => ({
	x: document.documentElement.clientWidth - 650
}));

const changeflowStatus = e => {
	if (e && searchState) {
		searchState.ids = e.ids;
		if (searchState.ids) {
			initData();
		}
	}
};

const { data, loading, run, current, pageSize, total } = usePagination(
	async params => {
		const search = { type: 1 };
		if (searchState.company_id) {
			if (!projectOptions.value.length) await getProjects();
			search.project_ids = projectOptions.value
				.filter(item => {
					return item.parseIds.includes(searchState.company_id);
				})
				.map(item => item.value)
				.join(",");
			if (!search.project_ids) {
				return [];
			}
		}
		return post("plan", { ...params, ...searchState, ...search });
	},
	{
		defaultParams: [
			{
				page_size: 10
			}
		],
		pagination: {
			currentKey: "page",
			pageSizeKey: "page_size",
			totalKey: "total"
		}
	}
);

const planSource = computed(() =>
	(data.value?.data || []).map(d => {
		if (d.children?.length === 0) delete d.children;

		return d;
	})
);

const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };
	const query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
	}
	router.replace({ query: {
		...query,
		...filters
	}})
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
if (query) {
	if (query.company_id) searchState.company_id = parseInt(query.company_id);
	if (query.project_id) searchState.project_id = parseInt(query.project_id);
	if (query.opr_id) searchState.opr_id = parseInt(query.opr_id);
	if (query.name) searchState.name = query.name;
	if (query.name) searchState.name = query.name;
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	initData(pag);
}

const editPlan = ({ id }) => {
	router.push(`plan/edit/${id}`);
};
const lookPlan = ({ id, project, code }) => {
	router.push(`plan/detail/${id}?&code=${code}`);
};
// const showPlan = ({ id }) => {
// 	router.push(`plan/info/${id}`);
// };
// 查看详情
const showPlan = ({ id, code }) => {
	// :href="`/#/plan/detail/${record.id}?&code=${record.code}`"
	router.push(`plan/detail/${id}?&code=${code}`);
};
const deletePlan = id => {
	proxy.$confirm({
		title: "确认提示",
		content: `确定要删除${typeof id === "number" ? "当前" : "选中"}的计划吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("plan/delete", { id })
				.then(() => {
					proxy.$message.success("计划删除成功");
					initData();
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		}
	});
};
</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}
</style>
